package com.yanmaohu.nikita.analyzer;

import com.yanmaohu.nikita.NikitaException;
import com.yanmaohu.nikita.data.expression.NameExpression;
import com.yanmaohu.nikita.data.structure.*;
import com.yanmaohu.nikita.scanner.SourceCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Bright Lee
 */
public class MemberAnalyzer {

    private final SourceCode sourceCode;
    private final StructureBody structureBody;

    public MemberAnalyzer(SourceCode sourceCode, StructureBody structureBody) {
        this.sourceCode = sourceCode;
        this.structureBody = structureBody;
    }

    public void analyze() {
        if (structureBody == null || structureBody.isEmpty()) {
            return;
        }
        //Map<String, FunctionStructureMember> functionMap = new HashMap<>();
        Map<String, StructureMember> substructureMap = new HashMap<>();
        Map<String, VariableMember> variableMap = new HashMap<>();
        for (int i = 0; i < structureBody.size(); i++) {
            Member member = structureBody.get(i);
            if (member instanceof FunctionMember) {
                FunctionMember functionStructureMember = (FunctionMember) member;
                // TODO
                continue;
            }
            if (member instanceof StructureMember) {
                StructureMember structureStructureMember = (StructureMember) member;
                NameExpression substructureName = structureStructureMember.getStructureName();
                String substructureNameString = substructureName.getContent();
                StructureMember structureStructureMember1 = substructureMap.get(substructureNameString);
                if (structureStructureMember1 != null) {
                    throw new NikitaException(sourceCode, substructureName.getBeginIndex(), substructureName.getEndIndex(), "Duplicate type name.");
                }
                substructureMap.put(substructureNameString, structureStructureMember);
                // TODO
                continue;
            }
            if (member instanceof VariableMember) {
                VariableMember variableStructureMember = (VariableMember) member;
                NameExpression variableName = variableStructureMember.getVariableName();
                String variableNameString = variableName.getContent();
                VariableMember variableStructureMember1 = variableMap.get(variableNameString);
                if (variableStructureMember1 != null) {
                    throw new NikitaException(sourceCode, variableName.getBeginIndex(), variableName.getEndIndex(), "Duplicate variable name.");
                }
                variableMap.put(variableNameString, variableStructureMember);
                // TODO
                continue;
            }
            throw new NikitaException(sourceCode, member.getBeginIndex(), member.getEndIndex(), "This structure member type is not supported.");
        }
    }

}
